﻿using System.Linq;
using Duality;
using Duality.Components;
using ClientApp.Avoidance;
using OpenTK;


namespace ClientApp
{
	[RequiredComponent(typeof(Transform))]
	public class Agent : Component, ICmpInitializable, ICmpUpdatable
	{
		private float radius;
		private Vector2 preferedVelocity;
		[System.NonSerialized]
		private HRVO hrvo;
		
		public ClientApp.Avoidance.HRVO Hrvo
		{
			get { return hrvo; }
		}
		public float Radius
		{
			get { return radius; }
			set { radius = value; }
		}
        public float ScaledRadius
        {
            get { return radius * (this.GameObj.Transform.Scale.X + this.GameObj.Transform.Scale.Y) * 0.5f; }
        }
		public OpenTK.Vector2 PreferedVelocity
		{
			get { return preferedVelocity; }
			set { preferedVelocity = value; }
		}

		void ICmpInitializable.OnInit(Component.InitContext context)
		{
			if (context == InitContext.Activate && AiManager.Instance != null)
			{
				hrvo = new HRVO(this);
                AiManager.Instance.RegisterAgent(this);
            }
		}
		void ICmpInitializable.OnShutdown(Component.ShutdownContext context)
		{
			if (context == ShutdownContext.Deactivate && AiManager.Instance != null)
				AiManager.Instance.RemoveAgent(this);
		}
		void ICmpUpdatable.OnUpdate()
        {
			this.GameObj.Transform.Vel += (new Vector3(hrvo.NewVelocity) - this.GameObj.Transform.Vel) * 0.25f * Time.TimeMult;
        }
	}
}
